{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# C05 程序的重要元素——语句\n",
    "\n",
    "\n"
   ]
  },
  {
   "source": [
    "## 5.1 print()\n",
    "\n",
    "注：使用模块 logging 来写入日志比使用 print() 更合适，Ref Ch19\n",
    "\n",
    "### 5.1.1 打印多个参数"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "age: 42\nHello, Mr. Gumby\nHello, Mr. Gumby\nHello,_Mr._Gumby\nHello, Mr. Gumby\n"
     ]
    }
   ],
   "source": [
    "# 打印多个参数，使用逗号分隔，系统会自动在参数之间插入一个空格字符\n",
    "print(\"age:\",42)\n",
    "name='Gumby'\n",
    "salutation='Mr.'\n",
    "greeting=\"Hello,\"\n",
    "print(greeting,salutation,name)\n",
    "greeting=\"Hello\"\n",
    "print(greeting+',',salutation,name)\n",
    "print(greeting+',',salutation,name,sep='_')\n",
    "print(greeting+',',end=' ')\n",
    "print(salutation,name)"
   ]
  },
  {
   "source": [
    "## 5.1 import()\n",
    "\n",
    "### 5.1.2 导入时重命名"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "2.0\n2.0\n"
     ]
    }
   ],
   "source": [
    "import math as mathematics\n",
    "\n",
    "print(mathematics.sqrt(4))\n",
    "\n",
    "from math import sqrt as square_root\n",
    "\n",
    "print(square_root(4))"
   ]
  },
  {
   "source": [
    "## 5.2 赋值\n",
    "\n"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "### 5.2.1 序列解包\n",
    "\n"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "1 2 3\n2 1 3\n1 2 3\n"
     ]
    }
   ],
   "source": [
    "x, y, z= 1, 2, 3\n",
    "print(x,y,z)\n",
    "\n",
    "x,y=y,x\n",
    "print(x,y,z)\n",
    "\n",
    "# 序列解包：也叫可迭代对象解包，将一个序列(或者任何可迭代的对象)解包，并将得到的值存储到一系列的变量中\n",
    "values=1,2,3\n",
    "x,y,z=values\n",
    "print(x,y,z)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "girlfriend: Marion\n"
     ]
    }
   ],
   "source": [
    "# 从字典中取出「键-值对」\n",
    "scoundrel={'name':'Robin', 'girlfriend':'Marion'}\n",
    "key, value=scoundrel.popitem()\n",
    "print(key+':', value)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "1 2 [3, 4, 5, 6]\n1 [2, 3, 4, 5] 6\n1 [2] 3\n"
     ]
    }
   ],
   "source": [
    "# 使用 * 号收集多余的值\n",
    "x,y, *rest = 1,2,3,4,5,6\n",
    "print(x,y,rest)\n",
    "x, *rest, z=1,2,3,4,5,6\n",
    "print(x,rest,z)\n",
    "x, *rest, z=1,2,3\n",
    "print(x,rest,z)"
   ]
  },
  {
   "source": [
    "### 5.2.2 链式赋值\n",
    "\n",
    "链式赋值是一种快捷方式，用于将多个变量关联到同一个值。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "1 1\n"
     ]
    }
   ],
   "source": [
    "x=y=1\n",
    "print(x,y)"
   ]
  },
  {
   "source": [
    "### 5.2.3 增强赋值\n",
    "\n",
    "适用于所有标准运算符，例如：+、-、*、/、**、%\n",
    "\n",
    "使用增强赋值，可以使代码更加简洁、易读"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "3\n6\n36\n"
     ]
    }
   ],
   "source": [
    "x=2\n",
    "x+=1\n",
    "print(x)\n",
    "x*=2\n",
    "print(x)\n",
    "x**=2\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "foobar\nfoobarfoobar\n"
     ]
    }
   ],
   "source": [
    "fnord='foo'\n",
    "fnord+='bar'\n",
    "print(fnord)\n",
    "fnord *=2\n",
    "print(fnord)"
   ]
  },
  {
   "source": [
    "## 5.3 代码块缩进\n",
    "\n",
    "代码块是一组语句，可以满足条件时执行。代码块是通过缩进代码来创建的。在同一个代码块中，各行代码的缩进量必须相同。代码块的声明使用冒号(：)"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "## 5.4 条件语句\n",
    "\n"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "### 5.4.1 布尔值\n",
    "\n"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "True\nTrue\n101\nTrue\nTrue\nbool('')= False\nbool(0)= False\nbool(())= False\nbool([])= False\n"
     ]
    }
   ],
   "source": [
    "# True 和 False 是 1 和 0 的别名\n",
    "print(True==1)\n",
    "print(False==0)\n",
    "print(100+True+False)\n",
    "print(bool(\"I think, therefore I am\"))\n",
    "print(bool(100))\n",
    "print(\"bool('')=\",bool(''))\n",
    "print(\"bool(0)=\",bool(0))\n",
    "print(\"bool(())=\",bool(()))\n",
    "print(\"bool([])=\",bool([]))"
   ]
  },
  {
   "source": [
    "### 5.4.2 if\n",
    "\n"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Hello, Mr. Gumby.\n"
     ]
    }
   ],
   "source": [
    "name=input(\"What is your name?\")\n",
    "if name.endswith('Gumby'):\n",
    "    print(\"Hello, Mr. Gumby.\")"
   ]
  },
  {
   "source": [
    "### 5.4.3 else\n",
    "\n"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Hello, stranger\n"
     ]
    }
   ],
   "source": [
    "name=input(\"What is your name?\")\n",
    "if name.endswith('Gumby'):\n",
    "    print(\"Hello, My. Gumby\")\n",
    "else:\n",
    "    print(\"Hello, stranger\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "stranger\n"
     ]
    }
   ],
   "source": [
    "# 条件表达式\n",
    "name=input(\"What is your name?\")\n",
    "status=\"firend\" if name.endswith('Gumby') else 'stranger'\n",
    "print(status)"
   ]
  },
  {
   "source": [
    "### 5.4.4 elif(else if)\n",
    "\n"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "The number is positive\n"
     ]
    }
   ],
   "source": [
    "num=int(input(\"Enter a number:\"))\n",
    "if num>0:\n",
    "    print(\"The number is positive\")\n",
    "elif num<0:\n",
    "    print(\"The number is negative\")\n",
    "else:\n",
    "    print(\"The number is zero\")"
   ]
  },
  {
   "source": [
    "### 5.4.5 代码块嵌套\n",
    "\n"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Hello, Mrs. Gumby\n"
     ]
    }
   ],
   "source": [
    "name=input(\"What is your name?\")\n",
    "if name.endswith('Gumby'):\n",
    "    if name.startswith('Mr.'):\n",
    "        print(\"Hello, Mr. Gumby\")\n",
    "    elif name.startswith('Mrs.'):\n",
    "        print(\"Hello, Mrs. Gumby\")\n",
    "    else:\n",
    "        print(\"Hello, Gumby\")\n",
    "else:\n",
    "    print(\"Hello, stranger\")"
   ]
  },
  {
   "source": [
    "### 5.4.6 复杂的条件\n",
    "\n",
    "表5-1：Python 比较运算符"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "True\nFalse\n"
     ]
    }
   ],
   "source": [
    "# 相等运算符\n",
    "print(\"foo\"==\"foo\")\n",
    "print(\"foo\"==\"bar\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "True\nTrue\nTrue\nFalse\n"
     ]
    }
   ],
   "source": [
    "# 相同运算符\n",
    "x=y=[1,2,3]\n",
    "z=[1,2,3]\n",
    "print(x==y)\n",
    "print(x==z)\n",
    "print(x is y)\n",
    "print(x is z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "True\n[1, 2]\n[1, 2]\nTrue\nFalse\n"
     ]
    }
   ],
   "source": [
    "x=[1,2,3]\n",
    "y=[2,4]\n",
    "print(x is not y)\n",
    "del x[2]\n",
    "y[1]=1\n",
    "y.reverse()\n",
    "print(x)\n",
    "print(y)\n",
    "print(x==y)\n",
    "print(x is y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Your name does nt containt the letter 's'.\n"
     ]
    }
   ],
   "source": [
    "# 成员资格运算符\n",
    "name=input(\"What is your name?\")\n",
    "if 's' in name:\n",
    "    print(\"Your name contains the letter 's'.\")\n",
    "else:\n",
    "    print(\"Your name does nt containt the letter 's'.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "True\nTrue\nTrue\n"
     ]
    }
   ],
   "source": [
    "# 字符串和序列的比较\n",
    "print(\"alpha\"<\"beta\")\n",
    "print([1,2]<[2,1])\n",
    "print([2,[1,4]]<[2,[1,5]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Great!\n"
     ]
    }
   ],
   "source": [
    "# 布尔运算符\n",
    "number=int(input(\"Enter a number between 1 and 10:\"))\n",
    "if number<=10:\n",
    "    if number>=1:\n",
    "        print(\"Great!\")\n",
    "    else:\n",
    "        print(\"Wrong!\")\n",
    "else:\n",
    "    print(\"Wrong!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "number=int(input(\"Enter a number between 1 and 10:\"))\n",
    "if number<=10 and number>=1:\n",
    "    print(\"Great!\")\n",
    "else:\n",
    "    print(\"Wrong!\")"
   ]
  },
  {
   "source": [
    "短路逻辑和条件表达式\n",
    "\n",
    "布尔运算符只做必要的计算，这种行为称为短路逻辑(或者延迟求值)"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "### 5.4.7 断言\n",
    "\n"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "age=10\n",
    "assert 0<age<100"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "age=-1\n",
    "# AssertionError\n",
    "# assert 0<age<100\n",
    "# assert 后面增加的字符串可以对断言做出说明\n",
    "# assert 0<age<100,\"The age must be realistic\""
   ]
  },
  {
   "source": [
    "## 5.5循环语句"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "### 5.5.1 while"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n"
     ]
    }
   ],
   "source": [
    "x=1\n",
    "while x<=10:\n",
    "    print(x)\n",
    "    x+=1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Hello, Tom\n"
     ]
    }
   ],
   "source": [
    "name=''\n",
    "while not name:\n",
    "    name=input('Please enter your name:')\n",
    "    pass\n",
    "print(\"Hello, {}\".format(name))"
   ]
  },
  {
   "source": [
    "### 5.5.2 for\n",
    "\n",
    "注：尽量使用 for 循环"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "this\nis\nan\nex\nparrot\n"
     ]
    }
   ],
   "source": [
    "words=['this','is','an','ex','parrot']\n",
    "for word in words:\n",
    "    print(word)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n"
     ]
    }
   ],
   "source": [
    "numbers=[0,1,2,3,4,5,6,7,8,9]\n",
    "for number in numbers:\n",
    "    print(number)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "range(0, 10)\nrange(0, 10)\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
     ]
    }
   ],
   "source": [
    "# 创建范围的内置函数\n",
    "print(range(10))\n",
    "print(range(0,10))\n",
    "print(list(range(0,10)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n"
     ]
    }
   ],
   "source": [
    "for number in range(0,10):\n",
    "    print(number)"
   ]
  },
  {
   "source": [
    "### 5.5.3 字典迭代\n",
    "\n",
    "注：字典元素的排列顺序是不确定的。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "x corresponds to 1\ny corresponds to 2\nz corresponds to 3\n---------使用字典方法获取所有值----------\nx corresponds to 1\ny corresponds to 2\nz corresponds to 3\n"
     ]
    }
   ],
   "source": [
    "d={'x':1,'y':2,'z':3}\n",
    "for key in d:\n",
    "    print(key,'corresponds to',d[key])\n",
    "    pass\n",
    "print(\"使用字典方法获取所有值\".center(30,'-'))\n",
    "for key,value in d.items():\n",
    "    print(key,'corresponds to',value)"
   ]
  },
  {
   "source": [
    "### 5.5.4 迭代工具\n",
    "\n",
    "帮助迭代序列(或者其他可迭代对象)的函数。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "anne is 12 years old.\nbeth is 45 years old.\ngeorge is 32 years old.\ndamon is 102 years old.\n----------zip() 缝合函数----------\n[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]\nanne is 12 years old.\nbeth is 45 years old.\ngeorge is 32 years old.\ndamon is 102 years old.\n---zip() 缝合不同长度的序列，取最短的序列缝合---\n[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]\n"
     ]
    }
   ],
   "source": [
    "# 1. 并行迭代\n",
    "names=['anne','beth','george','damon']\n",
    "ages=[12,45,32,102]\n",
    "\n",
    "for i in range(len(names)):\n",
    "    print(names[i],'is',ages[i],'years old.')\n",
    "    pass\n",
    "\n",
    "print(\"zip() 缝合函数\".center(30,'-'))\n",
    "print(list(zip(names,ages)))\n",
    "\n",
    "for name,age in zip(names,ages):\n",
    "    print(name,'is',age,'years old.')\n",
    "    pass\n",
    "\n",
    "print(\"zip() 缝合不同长度的序列，取最短的序列缝合\".center(30,'-'))\n",
    "print(list(zip(range(5),range(500))))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2. 使用内置函数 enumerate() 迭代时获取索引\n",
    "strings=['a xxx','b xxx','c','d']\n",
    "for string in strings:\n",
    "    if 'xxx' in string:\n",
    "        index=strings.index(string)\n",
    "        string[index]='[censored]'\n",
    "\n",
    "index=0\n",
    "strings=['a xxx','b xxx','c','d']\n",
    "for string in strings:\n",
    "    if 'xxx' in string:\n",
    "        strings[index]='[censored]'\n",
    "    index+=1\n",
    "\n",
    "strings=['a xxx','b xxx','c','d']\n",
    "for index,string in enumerate(strings):\n",
    "    if 'xxx' in string:\n",
    "        strings[index]='[censored]'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "[3, 3, 4, 6, 8]\n[' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']\n['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']\n!dlrow ,olleH\n[' ', '!', ',', 'd', 'e', 'H', 'l', 'l', 'l', 'o', 'o', 'r', 'w']\n"
     ]
    }
   ],
   "source": [
    "# 3. 反向迭代 和 排序后再迭代\n",
    "print(sorted([4,3,6,8,3]))\n",
    "hello_str='Hello, world!'\n",
    "print(sorted(hello_str))\n",
    "print(list(reversed(hello_str)))\n",
    "print(''.join(reversed(hello_str)))\n",
    "\n",
    "# 按字母表排序\n",
    "print(sorted(hello_str,key=str.lower))"
   ]
  },
  {
   "source": [
    "### 5.5.5 跳出循环"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "81\n"
     ]
    }
   ],
   "source": [
    "# 1. break：中断迭代后，直接跳出循环\n",
    "from math import sqrt\n",
    "for n in range(99,0,-1):\n",
    "    root=sqrt(n)\n",
    "    if root==int(root):\n",
    "        print(n)\n",
    "        break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "81\n64\n49\n36\n25\n16\n9\n4\n1\n"
     ]
    }
   ],
   "source": [
    "# 2. continue：中断迭代后，继续下一次迭代，而不跳出循环\n",
    "from math import sqrt\n",
    "for n in range(99,0,-1):\n",
    "    root=sqrt(n)\n",
    "    if root!=int(root):\n",
    "        continue\n",
    "    print(n)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "81\n"
     ]
    }
   ],
   "source": [
    "# whie True/break 中断迭代后，跳出无限循环\n",
    "from math import sqrt\n",
    "n=99\n",
    "while True:\n",
    "    n-=1\n",
    "    root=sqrt(n)\n",
    "    if root==int(root):\n",
    "        print(n)\n",
    "        break\n"
   ]
  },
  {
   "source": [
    "### 5.5.6 else 子句"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Didn't find it.\n"
     ]
    }
   ],
   "source": [
    "from math import sqrt\n",
    "for n in range(99,81,-1):\n",
    "    root=sqrt(n)\n",
    "    if root==int(root):\n",
    "        print(n)\n",
    "        break\n",
    "else:\n",
    "    print(\"Didn't find it.\")"
   ]
  },
  {
   "source": [
    "## 5.6 简单推导\n",
    "\n",
    "-   列表推导：基于 [] 实现。是一种从其他列表创建列表的方式，类似于数学中的集合推导。\n",
    "-   元组推导：无法基于 () 实现，基于 () 只能创建生成器。(Ref: Ch09)\n",
    "-   字典推导：基于 {} 实现。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n[0, 9, 36, 81]\n"
     ]
    }
   ],
   "source": [
    "# 列表推导\n",
    "print([x*x for x in range(10)])\n",
    "print([x*x for x in range(10) if x%3==0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "['chris+clarice', 'arnold+alice', 'bob+bernice']\n"
     ]
    }
   ],
   "source": [
    "boys=['chris','arnold','bob']\n",
    "girls=['alice','bernice','clarice']\n",
    "print([b+'+'+g for b in boys for g in girls if b[0]==g[0]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "{'a': ['alice'], 'b': ['bernice'], 'c': ['clarice']}\n['chris+clarice', 'arnold+alice', 'bob+bernice']\n"
     ]
    }
   ],
   "source": [
    "# 姓名匹配的更佳解决方案\n",
    "boys=['chris','arnold','bob']\n",
    "girls=['alice','bernice','clarice']\n",
    "letterGirls={}\n",
    "for girl in girls:\n",
    "    letterGirls.setdefault(girl[0],[]).append(girl)\n",
    "print(letterGirls)\n",
    "print([b+'+'+g for b in boys for g in letterGirls[b[0]]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "{0: '0 squared is 0', 1: '1 squared is 1', 2: '2 squared is 4', 3: '3 squared is 9', 4: '4 squared is 16', 5: '5 squared is 25', 6: '6 squared is 36', 7: '7 squared is 49', 8: '8 squared is 64', 9: '9 squared is 81'}\n"
     ]
    }
   ],
   "source": [
    "# 字典推导\n",
    "squares={i:\"{} squared is {}\".format(i,i**2) for i in range(10)}\n",
    "print(squares)"
   ]
  },
  {
   "source": [
    "## 5.7 三人行\n",
    "\n",
    "三条重要语句：\n",
    "\n",
    "-   pass\n",
    "-   del\n",
    "-   exec"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "### 5.7.1 pass：什么都不做\n",
    "\n",
    "在编写代码时，可将其用作占位符。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "### 5.7.2 del：删除\n",
    "\n",
    "对于不再使用的对象，既可以依赖 Python 进行内存管理；也可以使用 del 语句显式删除内存的占用，并且还会删除对象的名称。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "### 5.7.3 exec 执行字符串\n",
    "\n",
    "exec() 将字符串作为代码执行。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Hello, world!\n"
     ]
    }
   ],
   "source": [
    "exec(\"print('Hello, world!')\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "2.0\n2\n1\ndict_keys(['__builtins__', 'sqrt'])\n"
     ]
    }
   ],
   "source": [
    "# 未定义字符串代码的命名空间会造成污染\n",
    "# 使用字典定义字符串代码的命名空间\n",
    "from math import sqrt\n",
    "scope={}\n",
    "# scope=None\n",
    "exec('sqrt=1',scope)\n",
    "# exec('sqrt=1')\n",
    "print(sqrt(4))\n",
    "print(len(scope))\n",
    "print(scope['sqrt'])\n",
    "print(scope.keys())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "-----没有 print() 的 eval()------\nHello, world!\n-----前置 print() 的 eval()------\n7\nHello, world!\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n-----没有 print() 的 exec()------\nHello, world!\n-----前置 print() 的 exec()------\nNone\nNone\nHello, world!\nNone\n"
     ]
    }
   ],
   "source": [
    "### 5.7.3 eval 计算字符串表达式的值\n",
    "print(\"没有 print() 的 eval()\".center(30,'-'))\n",
    "eval(\"1+2*3\")\n",
    "eval(\"'Hello, world!'\")\n",
    "eval(\"[x for x in range(10)]\")\n",
    "eval(\"print('Hello, world!')\")\n",
    "\n",
    "print(\"前置 print() 的 eval()\".center(30,'-'))\n",
    "print(eval(\"1+2*3\"))\n",
    "print(eval(\"'Hello, world!'\"))\n",
    "print(eval(\"[x for x in range(10)]\"))\n",
    "\n",
    "print(\"没有 print() 的 exec()\".center(30,'-'))\n",
    "exec(\"1+2*3\")\n",
    "exec(\"[x for x in range(10)]\")\n",
    "exec(\"print('Hello, world!')\")\n",
    "print(\"前置 print() 的 exec()\".center(30,'-'))\n",
    "print(exec(\"1+2*3\"))\n",
    "print(exec(\"[x for x in range(10)]\"))\n",
    "print(exec(\"print('Hello, world!')\"))"
   ]
  },
  {
   "source": [
    "## 5.8 小结\n",
    "\n",
    "-   打印语句：print() 打印多个用逗号分隔的值。如果 print() 语句以逗号结尾，后续的 print() 会在当前行接着打印\n",
    "-   导入语句：导入需要的函数。利用`import...as...`在本地重命名函数\n",
    "-   赋值语句：\n",
    "    -   使用序列解包和链式赋值，可以同时给多个变量赋值\n",
    "    -   使用增强赋值，可以就地修改变量\n",
    "-   代码块：用于通过缩进将语句编组\n",
    "-   条件语句：根据条件(布尔表达式)决定是否执行后续的代码块\n",
    "-   断言：断定某件事(布尔表达式)为真，还可以包含说明字符串\n",
    "-   循环：\n",
    "    -   for：针对序列中的每个元素执行代码块\n",
    "    -   while：在条件为真时反复执行代码块\n",
    "    -   break：中断迭代，跳出循环\n",
    "    -   continue：中断迭代，执行下一个迭代，不跳出循环\n",
    "-   推导：推导是表达式\n",
    "    -   列表推导：可以从既有列表创建新的列表\n",
    "    -   字典推导：可以从既有列表创建新的字典\n",
    "-   占位符：pass，什么都不做\n",
    "-   删除语句：del，删除变量或者数据结构的成员，但是不能用于删除值\n",
    "-   执行字符串语句：\n",
    "    -   exec：将字符串作为 Python 语句执行\n",
    "    -   eval：将字符串作为表达式执行并返回结果"
   ],
   "cell_type": "markdown",
   "metadata": {}
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "3.6.12-final"
  },
  "pycharm": {
   "stem_cell": {
    "cell_type": "raw",
    "source": [],
    "metadata": {
     "collapsed": false
    }
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}